<template>
    <div class="e-form">
        <BillTop @cancel="handleClose"></BillTop>
        <div class="tabs warningTabs">
            <el-tabs
                tab-position="left"
                v-model="tabsName"
                @tab-click="onChangeTab"
            >
                <el-tab-pane
                    label="基本信息"
                    name="baseInfo"
                    :disabled="clickTabFlag"
                ></el-tab-pane>
                <el-tab-pane
                    label="汇总明细"
                    name="detailed"
                    :disabled="clickTabFlag"
                ></el-tab-pane>
                <el-tab-pane
                    label="附件信息"
                    name="attach"
                    :disabled="clickTabFlag"
                ></el-tab-pane>
                <el-tab-pane
                    label="审核历史"
                    name="auditHistory"
                    :disabled="clickTabFlag"
                ></el-tab-pane>
                <el-tab-pane
                    label="关联编号"
                    name="code"
                    :disabled="clickTabFlag"
                ></el-tab-pane>
                <div>
                    <div id="baseInfoCon" class="con">
                        <div class="tabs-title" id="baseInfo">基本信息</div>
                        <div style="width: 100%" class="form">
                              <el-form :model="basicForm" :label-width="formLabelWidth"
                       ref="ruleForm"
                             :rules="rules"
                             class="demo-ruleForm"
                    >
                        <el-row>
                                <el-col :span="12">
                               <el-form-item label="摊销汇总编号：">
                                    <span>{{ basicForm.billNo }}</span>
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                               <el-form-item label="所属机构：">
                                    <span>{{ basicForm.orgName }}</span>
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row>
                            <el-col :span="12">
                                  <el-form-item label="汇总日期：" >
                                      <span v-if="isRedSingle">
                                    {{
                                        basicForm.summaryDate
                                    }}
                                </span>
                                      <el-date-picker
                                              v-else
                                            value-format="yyyy-MM-dd"
                                            :clearable="false"
                                            type="date"
                                            placeholder="选择日期"
                                            v-model="basicForm.summaryDate"
                                        ></el-date-picker>
                                </el-form-item>
                            </el-col>

                            <el-col :span="12">
                               <el-form-item label="周材摊销：">
                                     <span v-if="isRedSingle">
                                    {{
                                        basicForm.amortizationNo
                                    }}
                                </span>
                                    <template v-else><el-button class="a" @click="selectBtn">选择周材摊销</el-button></template>
                                </el-form-item>
                            </el-col>

                        </el-row>
                        <el-row>
                            <el-col :span="12">
                                    <el-form-item label="状态：">
                                            <span>{{
                                                statusLable(basicForm.state)
                                            }}</span>
                                        </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="录入人：">
                                <span>
                                    {{
                                        basicForm.inputName
                                    }}
                                </span>
                                </el-form-item>
                            </el-col>

                        </el-row>
                        <el-row>
                            <el-col :span="12">
                                    <el-form-item label="摊销金额：">
                                            <span>{{
                                               basicForm.amount
                                            }}</span>
                                        </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="报销数量：">
                                <span>
                                    {{
                                        basicForm.quantity
                                    }}
                                </span>
                                </el-form-item>
                            </el-col>

                        </el-row>
                        <el-row>
                            <el-col :span="12">
                                    <el-form-item label="传财务共享：">
                                            <span>{{
                                               basicForm.isShare===0?'否':'是'
                                            }}</span>
                                        </el-form-item>
                            </el-col>
                        </el-row>

                                <el-row>
                                    <el-col :span="24">
                                        <el-form-item label="备注：">
                                            <el-input
                                                type="textarea"
                                                v-model="basicForm.remarks"
                                                autocomplete="off"
                                            ></el-input>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                  <el-row>
                        <el-form-item label="冲红单" v-if="isRedSingle"
                            ><span :style="redBillStateStyle">{{
                                redBillStateFun
                            }}</span></el-form-item
                        >
                    </el-row>
                    </el-form>
                        </div>
                    </div>
                    <!-- 汇总明细 -->
                    <div id="detailedCon" class="con">
                        <div class="tabs-title" id="detailed">汇总明细</div>
                        <div class="e-table">
                            <div class="errorMsg" v-if="errorMsg.length > 0">
                                <span
                                    v-for="(item, index) in errorMsg"
                                    :key="index"
                                >
                                    {{ item }}
                                </span>
                            </div>
                            <div class="e-tree-table">
                                    <el-table
                                class="table"
                                :data="detailedTableData"
                                border
                                style="width: 100%"
                                 :header-cell-style="{ textAlign: 'center' }"
                                :cell-style="{ textAlign: 'center' }"
                                :tree-props="{
                                    children: 'children',
                                    hasChildren: 'hasChildren'
                                }"
                                 row-key="dtlId"
                                :row-class-name="tableRowClassName"
                                :load="onload"
                                 :max-height="$store.state.tableHeight"
                                lazy
                                ref="table"
                                 v-sortTable="{ 'tableData': detailedTableData, '_this': this, 'ref': 'table' }"
                            >
                             <el-table-column  label="操作" width="200">
                    </el-table-column>
                                <el-table-column
                                    prop="materialClassName"
                                    label="类别"
                                    mini-width="300"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="materialName"
                                    label="物资名称"
                                    width="200"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="spec"
                                    label="规格"
                                    width="200"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="texture"
                                    label="材质"
                                    width="200"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="unit"
                                    label="计量单位"
                                    width="200"
                                >
                                </el-table-column>

                                <el-table-column
                                    prop="amount"
                                    label="摊销金额"
                                    width="200"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="quantity"
                                    label="报销数量"
                                    width="200"
                                >
                                </el-table-column>
                            </el-table>
                            </div>
                            <ComPagination />
                        </div>
                    </div>
                    <!-- 附件信息 -->
                    <div id="attachCon" class="con">
                        <div class="tabs-title" id="attach">附件信息</div>
                        <attach-comp
                            :relationId="attachId"
                            bucketName="turnover"
                            :isView="isRedSingle"
                        />
                    </div>
                    <!-- 审核历史 -->
                    <div id="auditHistoryCon" class="con">
                        <div class="tabs-title" id="auditHistory">审核历史</div>
                        <div class="e-table">
                            <ComAuditHistoryIndex
                                :billType="6100"
                                ref="AuditHistoryRef"
                            />
                        </div>
                    </div>
                    <!-- 关联编号 -->
                    <spam>{{test}}</spam>
                    <div id="codeCon">
                     <div class="tabs-title" id="code">关联编号</div>
                           <div class="e-table">
                               <el-table
                                  class="table"
                                :data="codeTableData"
                                border
                                style="width: 100%"
                               >
                                 <el-table-column
                                    prop="amortizationNo"
                                    label="摊销编号"
                                >
                                <template slot-scope="{ row, }">
                                        <span
                                            class="a"
                                            @click="linkToRevolveAmortize(row.amortizationId)"
                                        >
                                        {{
                                            row.amortizationNo
                                        }}
                                        </span>
                                    </template>
                                </el-table-column>
                                 <el-table-column
                                    prop="amortizationDate"
                                    label="摊销日期"
                                >
                                </el-table-column>
                                 <el-table-column
                                    prop="amortizationAmount"
                                    label="摊销金额"
                                >
                                </el-table-column>
                                 <el-table-column
                                    prop="amortizationQuantity"
                                    label="摊销数量"
                                >
                                </el-table-column>
                               </el-table>
                           </div>
                    </div>

                </div>
            </el-tabs>
        </div>
        <div class="buttons">
            <span class="tip"
                ><span style="color: red; margin-right: 0">*</span
                >为必填项</span
            >
     <ComExaButtons :auditState="auditState" :state="basicForm.state" @exas="exas" :founderId="basicForm.founderId" />
            <el-button size="small" @click="handleClose">关闭</el-button>
        </div>
        <div id="seat" :style="{ height: seatHeight + 'px' }"></div>
    </div>
</template>

<script>
import ComPagination from '@/components/pagination/pagination.vue'
import AttachComp from '@/components/common/attachIndex'
import { mapState } from 'vuex'
import ComAuditHistoryIndex from '@/pages/revolveMaterialManage/components/auditHistory/auditHistoryIndex'
import ComExaButtons from '@/components/common/exaButtons'
import { exas, saveAll, submitCommit } from '@/pages/revolveMaterialManage/common/revolveCom.js'

import { turnoverAmortizationGetAmortization } from '@/api/turnover/ppw.js'

import { openAppClient, } from '@/utils/common'
import auditRequest from '@/api/turnover/audit.js'

import otherRequest from '@/api/turnover/other.js'

import $ from 'jquery'
import '@/utils/jquery.scrollTo.min'
export default {
    components: {
        ComPagination,
        AttachComp,
        ComAuditHistoryIndex,
        ComExaButtons
    },
    computed: {
        // 填补底部空白，以使高度够滚动
        seatHeight () {
            return this.screenHeight - 72 - this.lastConHeight
        },
        attachId () {
            return this.billId
        },
        ...mapState({
            userInfo: state => state.userInfo,
            currencyForm: state => state.equip.equipData.currencyForm, //币种
            timeUnitList: state => state.equip.equipData.timeUnitList, //计时单位
            menuid: state => state.menuid
        }),
        statusLable () {
            return param => {
                const state = this.$store.state.equip.equipData.state
                const obj = state.find(x => x.value === param)
                if (obj !== undefined) {
                    return obj.label
                }
            }
        },
        // 红单状态
        redBillStateFun () {
            let redState = ''
            switch (this.basicForm.redState) {
            case 0:
                redState = '冲销中'
                break
            case 1:
                redState = '冲销中'
                break
            case 2:
                redState = '已冲销'
                break
            case 3:
                redState = '红单'
                break
            }
            return redState
        },
        // 关联编号
        codeTableData () {
            return this.basicForm.amortizationBill.length > 0 ? this.basicForm.amortizationBill : []
        }
    },
    watch: {
        //给错误标签加上提醒
        errorList: newData => {
            const tabs = document.querySelectorAll('.el-tabs__item')
            tabs.forEach(DOM => {
                const { childNodes } = DOM
                if (childNodes.length > 1) {
                    DOM.removeChild(childNodes[1])
                }
            })
            newData.forEach(item => {
                const itemDom = document.querySelector(`#tab-${item}`)
                var element = document.createElement('i')
                element.className = 'el-icon-warning-outline warning'
                itemDom.appendChild(element)
            })
        }
    },
    mounted () {
        this.getLastConHeight()
        // 保存所有tabName
        const arr = ['baseInfo', 'detailed', 'attach', 'auditHistory', 'code']
        this.tabArr = arr //标星星

        let $idsTop = []
        window.addEventListener('scroll', () => {
            // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            if (this.clickTabFlag) {
                return
            }

            if (!$idsTop[$idsTop.length - 1]) {
                $idsTop = arr.map(item => {
                    const itemTop = document.getElementById(item).offsetTop
                    return itemTop
                })
            }
            const scrollTop =
                document.documentElement.scrollTop || document.body.scrollTop
            // 倒序查找
            let curLocal = 0
            for (let len = $idsTop.length, i = len - 1; i >= 0; i--) {
                let item = $idsTop[i]
                if (scrollTop + 1 >= item) {
                    curLocal = i
                    break
                }
            }
            // 设置对应tabName
            this.tabsName = arr[curLocal]
        })

        this.screenWidth = document.documentElement.clientWidth - this.topHeight
        this.screenHeight = document.documentElement.clientHeight - this.topHeight
        window.addEventListener('resize', () => {
            this.screenWidth = document.documentElement.clientWidth - this.topHeight
            this.screenHeight = document.documentElement.clientHeight - this.topHeight
            $idsTop = arr.map(item => {
                const itemTop = document.getElementById(item).offsetTop
                return itemTop
            })
        })
        this.scorllDtl()
    },
    created () {
        this.billId = this.$route.query.billid
        // this.$route.query.isRedSingle === '1' ? this.isRedSingle = true : this.isRedSingle = false

        this.getBasicInfo()
        this.getCurrentUnitInfo()
        this.getDtlList()

    },
    data () {
        return {
            tabsName: 'baseInfo',
            screenWidth: 0,
            screenHeight: 0,
            lastConHeight: 0,
            clickTabFlag: false, // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            basicForm: {
                'amortizationBill': [
                    {
                        'amortizationId': '',
                        'amortizationNo': '',
                        'amortizationDate': ''
                    }
                ],
                'amount': 0,
                'billId': '',
                'billNo': '',
                'inputId': '',
                'inputName': '',
                'isShare': 0,
                'nullifyCreated': '',
                'nullifyCreator': '',
                'nullifyCreatorId': '',
                'nullifyDescription': '',
                'nullifyReason': '',
                'orgId': '',
                'orgName': '',
                'parentId': '',
                'quantity': 0,
                'redState': -1,
                'remarks': '',
                'state': 0,
                'summaryDate': '',
                'workId': ''
            },
            query: {
                limit: 10,
                number: '',
                orgname: '',
                page: 1,
                states: []
            },
            test: {},
            formLabelWidth: '150px',
            detailedTableData: [], //物资明细
            changeTableData: [], //变更信息
            basicInfo: {},
            stateArr: ['草稿', '审核中', '已审核', '已作废'],
            MouseEnterId: 0,
            showBaseCurName: true,
            rules: {
                summaryDate: [
                    {
                        required: true,
                        message: '请选择日期',
                    }
                ]
            },
            auditParams: {
                billId: this.$route.query.billid,

                billType: 6100,
                freeNextUnitIndex: 0,
                freeNextUser: '',
                isPass: true,
                isShareInAudit: true,
                opinion: ''
            },
            auditState: {},
            errorList: [], //控制导航栏感叹号的显示
            errorMsg: [],
            isErrorMsg: true, //是否提醒错误信息
            redBillStateStyle: {
                width: '300px',
                height: '30px',
                color: '#fff',
                backgroundColor: '#FF2300',
                'text-align': 'center'
            },
            isRedSingle: false,
            amortizationIdArr: [],

        }
    },
    methods: {
        //跳转到明细
        scorllDtl () {
            if (this.$route.query.name) {
                setTimeout(() => {
                    //因为dom异步加载，通过轮询找到渲染后的dom，获取高度
                    let obj = {
                        name: this.$route.query.name
                    }
                    this.tabsName = this.$route.query.name
                    this.onChangeTab(obj)
                }, 200)
            }
        },
        onChangeTab (e) {
            const height  = $('#' + e.name).offset().top
            $.scrollTo(height - this.topHeight, 500)
            // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            this.clickTabFlag = true
            // 动画结束后，恢复状态
            setTimeout(() => {
                this.clickTabFlag = false
            }, 600)
        },
        // 获取最后一个内容区域的高度，计算底部空白
        getLastConHeight () {
            let si = setInterval(() => {
                // 因为dom异步加载，通过轮询找到渲染后的dom，获取高度
                if (document.getElementById('recodesCon')) {
                    const lastConHeight =
                        document.getElementById('recodesCon').offsetHeight
                    console.log('lastConHeight: ', lastConHeight)
                    this.lastConHeight = lastConHeight
                    clearInterval(si)
                    si = null
                }
            }, 100)
        },
        getBasicInfo () {
            this.$Ajax
                .httpGet({
                    url: '/turnover/amortizationSummary/findById',
                    params: {
                        billId: this.billId
                    },
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded'
                    }
                })
                .then(res => {
                    res.redState === 3 ? this.isRedSingle = true : this.isRedSingle = false
                    for (let key in res) {
                        this.basicForm[key] = res[key]
                    }
                    this.amortizationIdArr = this.basicForm.amortizationBill.map(item=>item.amortizationId )
                })
        },
        getCurrentUnitInfo () {
            auditRequest.getCurrentUnitInfo(this.auditParams).then(res => {
                this.auditState = res
            })
        },
        getDtlList () {
            otherRequest
                .turnoverAmortizationSummaryGetDtlList(this.billId, '0')
                .then(res => {
                    if (res.length > 0) {

                        this.basicForm.amount = res[0].amount
                        this.basicForm.quantity = res[0].quantity
                        this.detailedTableData = res.map(v=>{
                            v.hasChildren = v.isDetails === 0 ? true : false
                            v.children = []
                            return v
                        })
                    }
                })
        },
        //更新基本信息
        updateBaseInfo () {
            return new Promise((resolve, reject) => {
                this.$refs.ruleForm.validate(valid => {
                    if (valid) {
                        otherRequest
                            .turnoverAmortizationSummaryUpdate(this.basicForm)
                            .then(() => {
                                // this.getBasicInfo() //更新基本信息
                                resolve()
                            })
                            .catch(err => {
                                this.setError('baseInfo')
                                reject(err)
                            })
                    } else {
                        this.setError('baseInfo')
                        this.scorllError()
                        return false
                    }
                })
            })
        },
        async exas (arg) {
            const requestFn = () => {
                return []
            }
            exas(arg, this, requestFn)
        },
        //保存全部数据
        saveAll () {
            const requestFn = ()=>{
                return [
                    this.updateBaseInfo(),

                ]
            }
            saveAll(this, requestFn)
        },
        submitCommit () {
            const requestFn = ()=>{
                return [
                    this.updateBaseInfo(),
                ]
            }
            submitCommit(this, requestFn)
        },

        toTree (data) {
            let result = []
            if (!Array.isArray(data)) {
                return result
            }
            data.forEach(item => {
                delete item.children
            })
            let map = {}
            data.forEach(item => {
                map[item.dtlId] = item
            })
            data.forEach(item => {
                let parent = map[item.parentId]
                if (parent) {
                    (parent.children || (parent.children = [])).push(item)
                } else {
                    result.push(item)
                }
            })
            return result
        },
        selectBtn () {
            turnoverAmortizationGetAmortization().then(res => {

                res.amortizationBill.forEach(v=>v.billId = this.billId)
                this.basicForm.amortizationBill = res.amortizationBill
                this.test = res.amortizationBill
                this.basicForm.amount = res.amount
                this.basicForm.quantity = res.quantity
                if(this.basicForm.amortizationBill.length > 0) {
                    this.amortizationIdArr = this.basicForm.amortizationBill.map(item=>item.amortizationId )
                    this.postSummaryDtl()
                }
            })
        },

        linkToRevolveAmortize (billid) {
            // 客户端弹窗弹出本地页面
            openAppClient(`/revolveAmortizeShow?billid=${billid}&isview=true`, '周材摊销')
        },
        // 汇总明细
        postSummaryDtl () {

            otherRequest.turnoverAmortizationSummarySummaryDtl({
                'billId': this.billId,
                'billIds': this.amortizationIdArr
            }).then(()=>{
                this.clientPop(
                    'suc',
                    '汇总明细成功',
                    this.getDtlList
                )
            })
        },
        async onload (row, treeNode, resolve) {
            otherRequest
                .turnoverAmortizationSummaryGetDtlList(row.billId, row.dtlId).then(res=>{
                    const arr = res.map(v=>{
                        v.hasChildren = v.isDetails === 0 ? true : false
                        return v
                    })
                    resolve(arr)
                })
        },
        onSave () {
            this.basicForm.isShare
                ? (this.basicForm.isShare = 1)
                : (this.basicForm.isShare = 0)

            this.$Ajax
                .httpPost({
                    url: '/turnover/allocation/update',
                    params: this.basicForm
                })
                .then(() => {
                    this.clientPop('suc', '修改成功', this.getBasicInfo)
                })
        },
        //点击删除
        clickDel () {
            this.clientPop(
                'info',
                '确定要删除吗？删除的数据可以在【回收站】还原或彻底删除。',
                this.delData
            )
        },
        delData () {
            this.$Ajax
                .httpGet({
                    url: '/turnover/amortizationSummary/delete',
                    params: { billId: this.billId },
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded'
                    }
                })
                .then(() => {
                    this.clientPop('suc', '删除成功', this.handleClose)
                })
        },
        upCount () {
            this.basicForm.allotAmount = 0
            if (this.detailedTableData.length > 0) {
                this.detailedTableData.forEach(v => {
                    v.children.forEach(item => {
                        if (v.changeType != -1 && item.money !== null) {
                            this.basicForm.allotAmount += parseInt(item.money)
                        }
                    })
                    const count = v.children.reduce(
                        (prev, c) => (prev += c.money || 0),
                        0
                    )
                    v.materialName = `小计： ${count}`
                })
            }
        },
        //判断当前状态是否已修改
        curStateChange (row) {
            this.curRow = row
            if (row.changeType !== 1) {
                {
                    this.curRow.changeType = 2
                }
            }

            // 计算剩余库存数量
            if (row.allocationQuantity) {
                row.money = row.allocationQuantity * row.price
            }
            this.upCount()
        },
        //点击删除的时候
        deleteEle (row) {
            row.changeType = -1
        },
        // 处理树
        tableRowClassName ({ row }) {
            if (row.children) {
                return 'warning-row'
            } else if (row.changeType === -1) {
                return 'row-hide'
            } else {
                return 'row-show'
            }
        },
        //设置错误标签
        setError (name) {
            if (!this.errorList.find(x => x === name)) {
                this.errorList.push(name)
            }
        },
        //跳转到第一个错误标签
        scorllError () {
            let num = this.tabArr.length
            this.errorList.forEach(item => {
                let index = this.tabArr.findIndex(x => x === item)
                num = index < num ? index : num
            })
            const obj = { name: this.tabArr[num] }
            this.tabsName = this.tabArr[num]
            this.onChangeTab(obj)
        },
        //计划明细非空验证
        verifyTable () {
            return new Promise((resolve, reject) => {
                this.errorMsg = []
                this.detailedTableData.forEach(v => {
                    v.children.forEach((item, index) => {
                        if (item.changeType !== -1) {
                            if (
                                item.allocationQuantity === '' ||
                                item.allocationQuantity === null
                            ) {
                                let str = `请填写第 ${index + 1} 行的调拨数量`
                                this.errorMsg.push(str)
                            }
                            if (
                                item.price === '' ||
                                item.price === null
                            ) {
                                let str = `请填写第 ${index + 1} 行的成本单价`
                                this.errorMsg.push(str)
                            }
                        }
                    })
                })

                if (this.errorMsg.length > 0) {
                    this.isErrorMsg = true
                    reject()
                } else {
                    this.isErrorMsg = false
                    resolve()
                }
            })
        },
        handleClose () {
            this.$router.push('/revolveAmortizationSummaryList')
        }
    }
}
</script>

<style lang="scss" scoped>
.e-table {
    min-height: auto;
    background: #fff;
}
.upload {
    margin: 20px auto;
    display: flex;
    justify-content: center;
    text-align: center;
}

.upload-demo {
    display: flex;
    justify-content: center;
    align-items: center;
}

::v-deep.el-input--suffix .el-input__inner {
    padding-right: 5px;
}
::v-deep.el-table .cell {
    text-align: center;
}
#iconEdit:hover {
    color: red;
}

.like {
    color: rgb(46, 97, 215);
    font-size: 17px;
    line-height: 30px;
    cursor: pointer;
}
</style>
